home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / json / decoder.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  11KB  |  370 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Implementation of JSONDecoder
  5. '''
  6. import re
  7. import sys
  8. from json.scanner import Scanner, pattern
  9.  
  10. try:
  11.     from _json import scanstring as c_scanstring
  12. except ImportError:
  13.     c_scanstring = None
  14.  
  15. __all__ = [
  16.     'JSONDecoder']
  17. FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
  18. NaN = float('nan')
  19. PosInf = float('inf')
  20. NegInf = float('-inf')
  21.  
  22. def linecol(doc, pos):
  23.     lineno = doc.count('\n', 0, pos) + 1
  24.     if lineno == 1:
  25.         colno = pos
  26.     else:
  27.         colno = pos - doc.rindex('\n', 0, pos)
  28.     return (lineno, colno)
  29.  
  30.  
  31. def errmsg(msg, doc, pos, end = None):
  32.     (lineno, colno) = linecol(doc, pos)
  33.     if end is None:
  34.         fmt = '{0}: line {1} column {2} (char {3})'
  35.         return fmt.format(msg, lineno, colno, pos)
  36.     (endlineno, endcolno) = linecol(doc, end)
  37.     fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
  38.     return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
  39.  
  40. _CONSTANTS = {
  41.     '-Infinity': NegInf,
  42.     'Infinity': PosInf,
  43.     'NaN': NaN,
  44.     'true': True,
  45.     'false': False,
  46.     'null': None }
  47.  
  48. def JSONConstant(match, context, c = _CONSTANTS):
  49.     s = match.group(0)
  50.     fn = getattr(context, 'parse_constant', None)
  51.     if fn is None:
  52.         rval = c[s]
  53.     else:
  54.         rval = fn(s)
  55.     return (rval, None)
  56.  
  57. pattern('(-?Infinity|NaN|true|false|null)')(JSONConstant)
  58.  
  59. def JSONNumber(match, context):
  60.     match = JSONNumber.regex.match(match.string, *match.span())
  61.     (integer, frac, exp) = match.groups()
  62.     fn = None if frac or exp else int
  63.     res = fn(integer)
  64.     return (res, None)
  65.  
  66. pattern('(-?(?:0|[1-9]\\d*))(\\.\\d+)?([eE][-+]?\\d+)?')(JSONNumber)
  67. STRINGCHUNK = re.compile('(.*?)(["\\\\\\x00-\\x1f])', FLAGS)
  68. BACKSLASH = {
  69.     '"': u'"',
  70.     '\\': u'\\',
  71.     '/': u'/',
  72.     'b': u'\x08',
  73.     'f': u'\x0c',
  74.     'n': u'\n',
  75.     'r': u'\r',
  76.     't': u'\t' }
  77. DEFAULT_ENCODING = 'utf-8'
  78.  
  79. def py_scanstring(s, end, encoding = None, strict = True, _b = BACKSLASH, _m = STRINGCHUNK.match):
  80.     if encoding is None:
  81.         encoding = DEFAULT_ENCODING
  82.     
  83.     chunks = []
  84.     _append = chunks.append
  85.     begin = end - 1
  86.     while None:
  87.         chunk = _m(s, end)
  88.         if chunk is None:
  89.             raise ValueError(errmsg('Unterminated string starting at', s, begin))
  90.         end = chunk.end()
  91.         (content, terminator) = chunk.groups()
  92.         if content:
  93.             if not isinstance(content, unicode):
  94.                 content = unicode(content, encoding)
  95.             
  96.             _append(content)
  97.         
  98.         if terminator == '"':
  99.             break
  100.         elif terminator != '\\':
  101.             if strict:
  102.                 msg = 'Invalid control character {0!r} at'.format(terminator)
  103.                 raise ValueError(errmsg(msg, s, end))
  104.             strict
  105.             _append(terminator)
  106.             continue
  107.         
  108.         
  109.         try:
  110.             esc = s[end]
  111.         except IndexError:
  112.             raise ValueError(errmsg('Unterminated string starting at', s, begin))
  113.  
  114.         if esc != 'u':
  115.             
  116.             try:
  117.                 m = _b[esc]
  118.             except KeyError:
  119.                 msg = 'Invalid \\escape: {0!r}'.format(esc)
  120.                 raise ValueError(errmsg(msg, s, end))
  121.  
  122.             end += 1
  123.         else:
  124.             esc = s[end + 1:end + 5]
  125.             next_end = end + 5
  126.             msg = 'Invalid \\uXXXX escape'
  127.             
  128.             try:
  129.                 if len(esc) != 4:
  130.                     raise ValueError
  131.                 len(esc) != 4
  132.                 uni = int(esc, 16)
  133.                 if uni <= uni:
  134.                     pass
  135.                 elif uni <= 56319 and sys.maxunicode > 65535:
  136.                     msg = 'Invalid \\uXXXX\\uXXXX surrogate pair'
  137.                     if not s[end + 5:end + 7] == '\\u':
  138.                         raise ValueError
  139.                     s[end + 5:end + 7] == '\\u'
  140.                     esc2 = s[end + 7:end + 11]
  141.                     if len(esc2) != 4:
  142.                         raise ValueError
  143.                     len(esc2) != 4
  144.                     uni2 = int(esc2, 16)
  145.                     uni = 65536 + (uni - 55296 << 10 | uni2 - 56320)
  146.                     next_end += 6
  147.                 
  148.                 m = unichr(uni)
  149.             except ValueError:
  150.                 raise ValueError(errmsg(msg, s, end))
  151.  
  152.             end = next_end
  153.         _append(m)
  154.         continue
  155.         return (u''.join(chunks), end)
  156.  
  157. if c_scanstring is not None:
  158.     scanstring = c_scanstring
  159. else:
  160.     scanstring = py_scanstring
  161.  
  162. def JSONString(match, context):
  163.     encoding = getattr(context, 'encoding', None)
  164.     strict = getattr(context, 'strict', True)
  165.     return scanstring(match.string, match.end(), encoding, strict)
  166.  
  167. pattern('"')(JSONString)
  168. WHITESPACE = re.compile('\\s*', FLAGS)
  169.  
  170. def JSONObject(match, context, _w = WHITESPACE.match):
  171.     pairs = { }
  172.     s = match.string
  173.     end = _w(s, match.end()).end()
  174.     nextchar = s[end:end + 1]
  175.     if nextchar == '}':
  176.         return (pairs, end + 1)
  177.     if nextchar != '"':
  178.         raise ValueError(errmsg('Expecting property name', s, end))
  179.     nextchar != '"'
  180.     end += 1
  181.     encoding = getattr(context, 'encoding', None)
  182.     strict = getattr(context, 'strict', True)
  183.     iterscan = JSONScanner.iterscan
  184.     while True:
  185.         (key, end) = scanstring(s, end, encoding, strict)
  186.         end = _w(s, end).end()
  187.         if s[end:end + 1] != ':':
  188.             raise ValueError(errmsg('Expecting : delimiter', s, end))
  189.         s[end:end + 1] != ':'
  190.         end = _w(s, end + 1).end()
  191.         
  192.         try:
  193.             (value, end) = iterscan(s, idx = end, context = context).next()
  194.         except StopIteration:
  195.             nextchar == '}'
  196.             nextchar == '}'
  197.             raise ValueError(errmsg('Expecting object', s, end))
  198.         except:
  199.             nextchar == '}'
  200.  
  201.         pairs[key] = value
  202.         end = _w(s, end).end()
  203.         nextchar = s[end:end + 1]
  204.         end += 1
  205.         if nextchar == '}':
  206.             break
  207.         
  208.         if nextchar != ',':
  209.             raise ValueError(errmsg('Expecting , delimiter', s, end - 1))
  210.         nextchar != ','
  211.         end = _w(s, end).end()
  212.         nextchar = s[end:end + 1]
  213.         end += 1
  214.         if nextchar != '"':
  215.             raise ValueError(errmsg('Expecting property name', s, end - 1))
  216.         nextchar != '"'
  217.     object_hook = getattr(context, 'object_hook', None)
  218.     if object_hook is not None:
  219.         pairs = object_hook(pairs)
  220.     
  221.     return (pairs, end)
  222.  
  223. pattern('{')(JSONObject)
  224.  
  225. def JSONArray(match, context, _w = WHITESPACE.match):
  226.     values = []
  227.     s = match.string
  228.     end = _w(s, match.end()).end()
  229.     nextchar = s[end:end + 1]
  230.     if nextchar == ']':
  231.         return (values, end + 1)
  232.     iterscan = JSONScanner.iterscan
  233.     while True:
  234.         
  235.         try:
  236.             (value, end) = iterscan(s, idx = end, context = context).next()
  237.         except StopIteration:
  238.             nextchar == ']'
  239.             nextchar == ']'
  240.             raise ValueError(errmsg('Expecting object', s, end))
  241.         except:
  242.             nextchar == ']'
  243.  
  244.         values.append(value)
  245.         end = _w(s, end).end()
  246.         nextchar = s[end:end + 1]
  247.         end += 1
  248.         if nextchar == ']':
  249.             break
  250.         
  251.         if nextchar != ',':
  252.             raise ValueError(errmsg('Expecting , delimiter', s, end))
  253.         nextchar != ','
  254.         end = _w(s, end).end()
  255.     return (values, end)
  256.  
  257. pattern('\\[')(JSONArray)
  258. ANYTHING = [
  259.     JSONObject,
  260.     JSONArray,
  261.     JSONString,
  262.     JSONConstant,
  263.     JSONNumber]
  264. JSONScanner = Scanner(ANYTHING)
  265.  
  266. class JSONDecoder(object):
  267.     '''Simple JSON <http://json.org> decoder
  268.  
  269.     Performs the following translations in decoding by default:
  270.  
  271.     +---------------+-------------------+
  272.     | JSON          | Python            |
  273.     +===============+===================+
  274.     | object        | dict              |
  275.     +---------------+-------------------+
  276.     | array         | list              |
  277.     +---------------+-------------------+
  278.     | string        | unicode           |
  279.     +---------------+-------------------+
  280.     | number (int)  | int, long         |
  281.     +---------------+-------------------+
  282.     | number (real) | float             |
  283.     +---------------+-------------------+
  284.     | true          | True              |
  285.     +---------------+-------------------+
  286.     | false         | False             |
  287.     +---------------+-------------------+
  288.     | null          | None              |
  289.     +---------------+-------------------+
  290.  
  291.     It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
  292.     their corresponding ``float`` values, which is outside the JSON spec.
  293.     '''
  294.     _scanner = Scanner(ANYTHING)
  295.     __all__ = [
  296.         '__init__',
  297.         'decode',
  298.         'raw_decode']
  299.     
  300.     def __init__(self, encoding = None, object_hook = None, parse_float = None, parse_int = None, parse_constant = None, strict = True):
  301.         '''``encoding`` determines the encoding used to interpret any ``str``
  302.         objects decoded by this instance (utf-8 by default).  It has no
  303.         effect when decoding ``unicode`` objects.
  304.  
  305.         Note that currently only encodings that are a superset of ASCII work,
  306.         strings of other encodings should be passed in as ``unicode``.
  307.  
  308.         ``object_hook``, if specified, will be called with the result of
  309.         every JSON object decoded and its return value will be used in
  310.         place of the given ``dict``.  This can be used to provide custom
  311.         deserializations (e.g. to support JSON-RPC class hinting).
  312.  
  313.         ``parse_float``, if specified, will be called with the string
  314.         of every JSON float to be decoded. By default this is equivalent to
  315.         float(num_str). This can be used to use another datatype or parser
  316.         for JSON floats (e.g. decimal.Decimal).
  317.  
  318.         ``parse_int``, if specified, will be called with the string
  319.         of every JSON int to be decoded. By default this is equivalent to
  320.         int(num_str). This can be used to use another datatype or parser
  321.         for JSON integers (e.g. float).
  322.  
  323.         ``parse_constant``, if specified, will be called with one of the
  324.         following strings: -Infinity, Infinity, NaN, null, true, false.
  325.         This can be used to raise an exception if invalid JSON numbers
  326.         are encountered.
  327.  
  328.         '''
  329.         self.encoding = encoding
  330.         self.object_hook = object_hook
  331.         self.parse_float = parse_float
  332.         self.parse_int = parse_int
  333.         self.parse_constant = parse_constant
  334.         self.strict = strict
  335.  
  336.     
  337.     def decode(self, s, _w = WHITESPACE.match):
  338.         '''
  339.         Return the Python representation of ``s`` (a ``str`` or ``unicode``
  340.         instance containing a JSON document)
  341.  
  342.         '''
  343.         (obj, end) = self.raw_decode(s, idx = _w(s, 0).end())
  344.         end = _w(s, end).end()
  345.         if end != len(s):
  346.             raise ValueError(errmsg('Extra data', s, end, len(s)))
  347.         end != len(s)
  348.         return obj
  349.  
  350.     
  351.     def raw_decode(self, s, **kw):
  352.         '''Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
  353.         with a JSON document) and return a 2-tuple of the Python
  354.         representation and the index in ``s`` where the document ended.
  355.  
  356.         This can be used to decode a JSON document from a string that may
  357.         have extraneous data at the end.
  358.  
  359.         '''
  360.         kw.setdefault('context', self)
  361.         
  362.         try:
  363.             (obj, end) = self._scanner.iterscan(s, **kw).next()
  364.         except StopIteration:
  365.             raise ValueError('No JSON object could be decoded')
  366.  
  367.         return (obj, end)
  368.  
  369.  
  370.